package 分类.二叉树;

import java.util.LinkedList;

public class 二叉树的序列化与反序列化 {
    String SEP=",";
    String NULL="#";
    public String serialize(TreeNode root) {
      StringBuilder sb=new StringBuilder();
      serialized(root,sb);
      return sb.toString();
    }

    void serialized(TreeNode node,StringBuilder sb){
        if(node==null){
            sb.append(NULL).append(SEP);
            return;
        }
        sb.append(node.val).append(SEP);
        serialized(node.left,sb);
        serialized(node.right,sb);
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        LinkedList<String> list=new LinkedList<>();
        for (String s:data.split(SEP)){
            list.add(s);
        }
        TreeNode root=deserialized(list);
        return root;
    }

    TreeNode deserialized(LinkedList<String> list){
        if(list.isEmpty()) return null;
        String first=list.getFirst();
        if(first.equals(NULL)) return null;
        TreeNode node=new TreeNode(Integer.valueOf(first));
        node.left=deserialized(list);
        node.right=deserialized(list);
        return node;
    }
}
